package com.jackrain.nea.shiro.stateful;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.cp.api.ChrusersModifypwdCmd;
import com.jackrain.nea.dao.UserReposity;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ReferenceUtil;
import com.jackrain.nea.util.ShiroSessionUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.LoadUserenvCmd;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.face.impl.UserImpl;
import com.jackrain.nea.web.security.Security4Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Locale;


/**
 * @author xubin
 * 2017-11-23
 */
@Slf4j
@Component
public class LDAPRealm extends AuthorizingRealm {

    @Autowired
    private UserReposity userReposity;

    private ChrusersModifypwdCmd chrusersModifypwdCmd;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        String userName=token.getUsername();
        String password=new String(token.getPassword());
        Locale locale= LocaleContextHolder.getLocale();
        if(userReposity.authenticate(userName,password)){
            User user = null;
            try {
                user = Security4Utils.getUser(token.getUsername());
                LoadUserenvCmd loadUserenvCmd = (LoadUserenvCmd)ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), "com.jackrain.nea.web.LoadUserenvCmd", "cp", "1.0");
                user.setUserenv(loadUserenvCmd.getUserenv(user));
//                user.setUserenv(QueryUtils.getUserenv(user));
                ((UserImpl)user).setLocale(locale);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }



            JSONObject jo=new JSONObject();
            jo.put("objid",user.getId());
            jo.put("name",user.getName());
            jo.put("newpassword",password);

//            JSONObject fixcolumn=new JSONObject();
//            JSONObject entity=new JSONObject();
//            entity.put("PASSWORD",password);
//            fixcolumn.put("CP_C_HRUSERS",entity);
//            jo.put("fixcolumn",fixcolumn);
//            jo.put("table","CP_C_HRUSERS");
//            QuerySession qsession = QueryUtils.createQuerySession(user);
//            DefaultWebEvent event = new DefaultWebEvent("doSave", ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(), false);

//            event.put("param", jo);

            try {
                HashMap<String,Object> param = Maps.newHashMap();
                param.put("param",jo);

                chrusersModifypwdCmd =(ChrusersModifypwdCmd) ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(),"com.jackrain.nea.cp.api.ChrusersModifypwdCmd","cp","1.0");
//                qsession.setEvent(event);
                chrusersModifypwdCmd.execute(param);
                user= Security4Utils.getUser(userName);

            } catch (Exception e) {
                log.error(Resources.getMessage("密码更新失败，")+e.getMessage(),e);
            }
            AuthenticationInfo info = new SimpleAuthenticationInfo(user,password, getName());
            return info;
        }else {
            ValueHolder vh = new ValueHolder();
            vh.put("code",-1);
            vh.put("message","AD域用户不存在或者密码错误！");
            ShiroSessionUtil.setAttribute("vh",vh);
        }



        return null;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
